﻿using System;
using System.Linq;
using Notoric.Commanding;
using Notoric.Gui.Windows;
using Notoric.ViewModel.Elements.CWNotation;

namespace Notoric.Gui.Commands
{
    /// <summary>
    /// Implements a command that creates slur(s) connecting selected chords.
    /// </summary>
    public class SlurChordsCommand : MusicSelectionRibbonCommand
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="SlurChordsCommand"/> class.
        /// </summary>
        /// <param name="mainWindow">
        /// <para>
        /// Type: <see cref="MainWindow"/>
        /// </para>
        /// <para>
        /// The main application window.
        /// </para>
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="mainWindow"/> is <see langword="null"/>.
        /// </exception>
        public SlurChordsCommand(MainWindow mainWindow)
            : base(mainWindow)
        {
            ScreenTipTitle = "Slur Notes";
            ScreenTipText = "Connects a selected group of notes by a slur (legato).";
            DisableReason = "Select two or more notes first.";
        }

        #endregion

        #region MusicSelectionRibbonCommand Members

        /// <inheritdoc/>
        protected override bool CanExecuteCore(object parameter)
        {
            return Selection != null && Selection.Count(s => s is Chord) > 1;
        }

        #endregion

        #region ICommand Members

        /// <inheritdoc/>
        public override void Execute(object parameter)
        {
            var symbols = Selection.GroupByPart();
            var macro = new UndoableMacroCommand(ApplicationWindow.StackManager.ActiveUndoStack, ApplicationWindow.StackManager.ActiveRedoStack)
            {
                Name = "Slur Notes"
            };

            foreach (var gr in symbols)
            {
                var ordered = from symbol in gr.Symbols.OrderByBeat()
                              where symbol is Chord
                              group symbol by ((Chord)symbol).Voice into g
                              select g;

                foreach (var fs in ordered)
                {
                    var beginning = (Chord)fs.First();
                    var end = (Chord)fs.Last();
                    if (beginning == end)
                        continue;

                    var cmd = new ViewModel.SlurChordsCommand(ApplicationWindow.StackManager.ActiveUndoStack, ApplicationWindow.StackManager.ActiveRedoStack)
                    {
                        Start = beginning,
                        End = end
                    };
                    macro.Commands.Add(cmd);
                }
            }

            macro.Execute(null);
        }

        #endregion
    }
}
